#include "UserSevice.h"
#include "../CinUserMap.h"
//#include "../bean/User.h"
#include "../utils/Utils.h"

UserSevice::UserSevice(/* args */)
{
}

UserSevice::~UserSevice()
{
}

 void UserSevice::doHandle(const char *pDataBuffer)
 {
   pLogin = (NetPacket_Login *)pDataBuffer;
   std::cout << "UserSevice::doHandle==pLogin->nIndex=" << pLogin->uid << "  pLogin->arrMessage " << pLogin->arrMessage << std::endl;  
    
  	char	uname[512];
   strncpy(uname, pLogin->arrMessage, 512);

   time_t myt=time(NULL);
  
   string str_id = Utils::time_t2str(myt);   
	string str_n = uname; 
   string str_t = str_id+"|"+str_n;

   cout <<" str_t:" << str_t<< endl;
   replyLogin(str_id.c_str(), str_n.c_str());
   
   CinUserMap::GetInstance()->addMap(peerfd, str_t);
   
   replyEmployee();
   //free(pDataBuffer);
 }


/**
 *  登录响应
 * */
void UserSevice::replyLogin(const char *uid,const char *msg)
{     
   NetPacket_RepLogin vData;
   
   cout <<" UserSevice::replyLogin peerfd:" << peerfd<< endl;
   strncpy(vData.uid, uid, sizeof(vData.uid));    
   strncpy(vData.arrMessage, msg, sizeof(vData.arrMessage));
   mSocket->send(peerfd, REP_LOGIN, (const char*)&vData, sizeof(vData));            
      
}

/**
 *  同步用户信息给所有在线用户
 * */
void UserSevice::replyEmployee()
{     
   NetPacket_RepEmployee vData;
   list<int>::iterator it, it1;   
   list<int> lists = CinUserMap::GetInstance()->getClients();
   for(it = lists.begin(); it != lists.end() ; it++)
   { 
      int fd = *it;
      string user = CinUserMap::GetInstance()->findUser(fd);
      cout << user << endl;
      for(it1 = lists.begin(); it1 != lists.end() ; it1++){
         if(fd == *it1) continue;
        
         strncpy(vData.arrMessage, user.c_str(), sizeof(vData.arrMessage));
         mSocket->send(*it1, REP_EMPLOYEE, (const char*)&vData, sizeof(vData));            
      }
   }
}
